﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.IO;
using Facebook;

namespace iMagistic
{
    /// <summary>
    /// Interaction logic for PhotoLoader.xaml
    /// </summary>
    public partial class PhotoLoader : UserControl
    {
        public event EventHandler FolderSelectedEvent;
        List<FacebokFolder> FacebookImageFolders;
        FacebookOAuthResult result;
        public PhotoLoader()
        {
            InitializeComponent();
        
        }

        private void menuItem_Click(object sender, RoutedEventArgs e)
        {
            Button menubutton = sender as Button;

            FolderListCtrl.Items.Clear();
            delimiterImage.Visibility = System.Windows.Visibility.Hidden;
            delimiterRectangle.Visibility = System.Windows.Visibility.Hidden;

            switch (menubutton.Name)
            {
                case "menuItem1":   MessageBox.Show("1");
                                    break;

                case "menuItem2":   MessageBox.Show("2");
                                    break;

                case "menuItem3":   var dbPath = System.IO.Path.Combine(
                                    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Dropbox" + Path.DirectorySeparatorChar.ToString() + "host.db");

                                    string[] lines = System.IO.File.ReadAllLines(dbPath);
                                    byte[] dbBase64Text = Convert.FromBase64String(lines[1]);
                                    string folderPath = System.Text.ASCIIEncoding.ASCII.GetString(dbBase64Text);

                                    folderPath += Path.DirectorySeparatorChar.ToString() + "Camera Uploads";
                                    ImportFromFolder(folderPath);
                                    break;

                case "menuItem4": 
                                    var fbClient = new FacebookModule();
                                    fbClient.ShowDialog();
                                    result = fbClient.FacebookOAuthResult;
                                    if (result == null) return;

                                    if (result.IsSuccess)
                                    {
                                        this.FacebookImageFolders = fbClient.GetFacebookFolders();
                                        if (FacebookImageFolders.Count > 1)
                                        {
                                            FolderListCtrl.Visibility = System.Windows.Visibility.Visible;
                                            foreach (FacebokFolder Ffolder in FacebookImageFolders)
                                            {
                                                imageFolder imFolder = new imageFolder();
                                                imFolder.FullPath = "facebook+" + FacebookImageFolders.IndexOf(Ffolder).ToString();
                                                imFolder.Name = Ffolder.Name;
                                                FolderListCtrl.Items.Add(imFolder);
                                            }
                                            delimiterImage.Visibility = System.Windows.Visibility.Visible;
                                            delimiterRectangle.Visibility = System.Windows.Visibility.Visible;
                                        }

                                    }

                                    break;

                case "menuItem5":   string path = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
                                    ImportFromFolder(path);
                                    break;
            }

        }

        private void RaiseFolderSelectedEvent(List<string> imagelist)
        {
            if (this.FolderSelectedEvent != null)
                this.FolderSelectedEvent(imagelist, new EventArgs());
        }

        private void FolderButton_Click(object sender, RoutedEventArgs e)
        {
            Button cmd = (Button)sender;
            imageFolder imFolder;
            List<string> imagelist;

            if (cmd.DataContext is imageFolder)
            {
                imFolder = (imageFolder)cmd.DataContext;
                if (imFolder.FullPath.Contains("facebook"))
                {
                    string[] numberArr = imFolder.FullPath.Split(new char[] { '+' });
                    int position = -1;
                    int.TryParse(numberArr[1], out position);

                    FacebokFolder tmpFf = FacebookImageFolders[position];

                    var fbClient = new FacebookModule();
                    fbClient = new FacebookModule(tmpFf, result);
                    fbClient.ShowDialog();

                    imagelist = fbClient.photoPaths;

                    if (imagelist.Count > 0)
                    {
                        RaiseFolderSelectedEvent(imagelist);
                    }
                    delimiterImage.Visibility = System.Windows.Visibility.Hidden;
                    delimiterRectangle.Visibility = System.Windows.Visibility.Hidden;
                    fbClient.Close();
                    return;

                }

                imagelist = filterImageFiles(new string[] { imFolder.FullPath });
                RaiseFolderSelectedEvent(imagelist);
            }
        }

        private void ImportFromFolder(string folderPath)
        {

            FolderListCtrl.Items.Clear();

            if (!Directory.Exists(folderPath)) return;

            List<string> imageFolders = GetChildImageFolders(folderPath);

            if (imageFolders.Count == 1)
            {
                List<string> imagelist = filterImageFiles(new string[] { folderPath });
                RaiseFolderSelectedEvent(imagelist);
            }
            else
                if (imageFolders.Count > 0)
                {
                    FolderListCtrl.Visibility = System.Windows.Visibility.Visible;
                    foreach (string path in imageFolders)
                    {
                        imageFolder imFolder = new imageFolder();
                        imFolder.FullPath = path;
                        imFolder.Name = Path.GetFileName(path);
                        FolderListCtrl.Items.Add(imFolder);
                    }
                    delimiterImage.Visibility = System.Windows.Visibility.Visible;
                    delimiterRectangle.Visibility = System.Windows.Visibility.Visible;
                }
        }

        /// <summary>
        /// will parse the given files, and will return all images contained in folders and subfolders.
        /// used for Drag & Drop
        /// </summary>
        public List<string> filterImageFiles(string[] FileList)
        {

            List<string> imagelist = new List<string>();

            foreach (string FilePath in FileList)
            {
                //MessageBox.Show(FilePath.ToString());

                // get the file attributes for file or directory
                FileAttributes attr = File.GetAttributes(FilePath);

                //detect whether its a directory
                if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
                {
                    //MessageBox.Show("Its a directory");

                    imagelist.AddRange(Directory.GetFiles(FilePath, "*.jpg"));
                    //imagelist.AddRange(Directory.GetFiles(FilePath, "*.JPG"));

                    try
                    {
                        DirectoryInfo[] dirs;
                        dirs = new DirectoryInfo(FilePath).GetDirectories("*.*", SearchOption.AllDirectories);

                        foreach (var dir in dirs)
                        {
                            string path = dir.FullName;
                            if (path.Length > 0)
                            {
                                //MessageBox.Show(path);
                                imagelist.AddRange(Directory.GetFiles(path, "*.jpg"));
                               // imagelist.AddRange(Directory.GetFiles(FilePath, "*.JPG"));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
                else
                {
                    if (FilePath.EndsWith(".jpg") || FilePath.EndsWith(".JPG"))
                    {
                        imagelist.Add(FilePath);
                    }
                }
            }
            return imagelist;
        }

        public List<string> GetChildImageFolders(string FilePath)
        {

            List<string> imageFolders = new List<string>();

            List<string> tmp = new List<string>();

            tmp.AddRange(Directory.GetFiles(FilePath, "*.jpg"));
            tmp.AddRange(Directory.GetFiles(FilePath, "*.JPG"));

            if (tmp.Capacity > 0) imageFolders.Add(FilePath);
            tmp.Clear();

            try
            {
                DirectoryInfo[] dirs;
                dirs = new DirectoryInfo(FilePath).GetDirectories("*.*", SearchOption.AllDirectories);

                foreach (var dir in dirs)
                {
                    string path = dir.FullName;
                    if (path.Length > 0)
                    {
                        tmp.AddRange(Directory.GetFiles(path, "*.jpg"));
                        tmp.AddRange(Directory.GetFiles(path, "*.JPG"));
                        if (tmp.Count > 0) imageFolders.Add(path);
                        tmp.Clear();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            return imageFolders;
        }

    }

    public class imageFolder
    {
        public string FullPath { get; set; }
        public string Name { get; set; }
    }

}
